;(function(doc, tpl, tools){

  function myTab(el){
    this.el = doc.getElementById(el);
    this.data = JSON.parse(this.el.getAttribute('data'));
    this._index = 0;
  }

  myTab.prototype.init = function(){
    this._render();
    this._binEvent();
  }

  // 渲染数据
  myTab.prototype._render = function(){
    var tabWrapper = doc.createElement('div');
    var pageWrapper = doc.createElement('div');
    var oFrag = doc.createDocumentFragment();

    tabWrapper.className = ' tab-Wrapper';
    pageWrapper.className = 'pageWrapper';

    this.data.forEach(function (item, index){
      tabWrapper.innerHTML += tools.tplReplace(tpl.tab('tab'), {
        tab: item.tab,
        current: !index ? 'current' : ''
      });

      pageWrapper.innerHTML += tools.tplReplace(tpl.tab('page'), {
        tab: item.page,
        current: !index ? 'current' : ''
      });

    });

    oFrag.appendChild(tabWrapper);
    oFrag.appendChild(pageWrapper);
    
    this.el.appendChild(oFrag);
  }

  myTab.prototype._binEvent = function(){
    var doms = {
      tabWrapper: doc.getElementsByClassName('tab-Wrapper')[0],
      tabItems: doc.getElementsByClassName('tab-item'),
      pageItems: doc.getElementsByClassName('page-item')
    }

    doms.tabWrapper.addEventListener('click', this._headleTabClick.bind(this, doms), false);
  }

  myTab.prototype._headleTabClick = function(){
    var _doms = arguments[0],
      tar = arguments[1].target,
      className = tar.className.trim();
    
    console.log(_doms, tar, className, arguments[1]);
    if(className === 'tab-item'){
      _doms.tabItems[this._index].className = 'tab-item';
      _doms.pageItems[this._index].className = 'page-item';
      this._index = [].indexOf.call(_doms.tabItems, tar);
      _doms.tabItems[this._index].className += ' current';
      _doms.pageItems[this._index].className += ' current';
    }
  }

  window.myTab = myTab;
})(document, tpl, tools)




